package com.le.ui;

import com.le.component.BackGroundPanel;
import com.le.util.InsertDataToSql;
import com.le.util.Query;
import com.le.util.RandomAdd;
import com.le.util.ScreenUtils;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class GradeAddPage {
    String hostIdAddress;
    JFrame jFrame = new JFrame("成绩录入");
    BackGroundPanel backGroundPanel = new BackGroundPanel(new ImageIcon("images//背景-10.png").getImage());
    final int WIDTH = 720;
    final int HEIGHT = 480;
    Map<String, String[]> majors = RandomAdd.MAJOR;

    public static Map<String, Integer> SUBJECT = new HashMap<>();

    static {
        SUBJECT.put("数学", 0);
        SUBJECT.put("Java", 1);
        SUBJECT.put("体育", 2);
        SUBJECT.put("英语", 3);
    }


    JLabel facultyLabel = new JLabel("请选择院系:");
    JComboBox<String> facultyComboBox = new JComboBox<>(RandomAdd.FACULTY);

    JLabel majorLabel = new JLabel("请选择专业:");
    JComboBox<String> majorComboBox = new JComboBox<>(majors.get("信息技术与管理学院"));

    JLabel classLabel = new JLabel("请选择班级:");
    JComboBox<String> classComboBox = new JComboBox<>();

    JLabel subject = new JLabel("请选择科目:");
    String[] subjects = new String[]{"数学", "Java", "体育", "英语"};
    JComboBox<String> subjectComboBox = new JComboBox<>(subjects);

    JButton add = new JButton("确      定");

    public GradeAddPage(String hostIdAddress) {
        this.hostIdAddress = hostIdAddress;
    }


    public void init() {
        //组装视图
        jFrame.setIconImage(new ImageIcon("images/成绩.png").getImage());
        jFrame.setBounds((ScreenUtils.getScreenWidth() - WIDTH) / 2,
                (ScreenUtils.getScreenHeight() - HEIGHT) / 2, WIDTH, HEIGHT);

        Box faultyBox = Box.createHorizontalBox();
        faultyBox.add(facultyLabel);
        faultyBox.add(Box.createHorizontalStrut(10));
        faultyBox.add(facultyComboBox);

        Box majorBox = Box.createHorizontalBox();
        majorBox.add(majorLabel);
        majorBox.add(Box.createHorizontalStrut(10));
        majorBox.add(majorComboBox);

        Box classChoiceBox = Box.createHorizontalBox();
        classChoiceBox.add(classLabel);
        classChoiceBox.add(Box.createHorizontalStrut(10));
        classChoiceBox.add(classComboBox);

        // classChoiceBox默认展开计算机科学与技术的班级
        String selectedMajor = majorComboBox.getSelectedItem().toString();
        Query query = new Query(hostIdAddress);
        query.setDatabaseName("sams");
        query.setSQL("select distinct class from student where major=" + "'" + selectedMajor + "'");
        String[][] result = query.getRecord();
        for (String[] strings : result) {
            classComboBox.addItem(selectedMajor + strings[0] + "班");
        }

        Box subjectBox = Box.createHorizontalBox();
        subjectBox.add(subject);
        subjectBox.add(Box.createHorizontalStrut(10));
        subjectBox.add(subjectComboBox);

        Box btnBox = Box.createHorizontalBox();
        add.setPreferredSize(new Dimension(80, 30));
        btnBox.add(add);

        Box content = Box.createVerticalBox();
        content.add(Box.createVerticalStrut(78));
        content.add(faultyBox);
        content.add(Box.createVerticalStrut(20));
        content.add(majorBox);
        content.add(Box.createVerticalStrut(20));
        content.add(classChoiceBox);
        content.add(Box.createVerticalStrut(20));
        content.add(subjectBox);
        content.add(Box.createVerticalStrut(40));
        content.add(btnBox);

        backGroundPanel.add(content);

        jFrame.add(backGroundPanel);
        jFrame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        jFrame.setResizable(false);
        jFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        jFrame.setVisible(true);

        //事件处理
        facultyComboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    String[] major = majors.get(facultyComboBox.getSelectedItem().toString());
                    majorComboBox.removeAllItems();
                    for (String majorItem : major) {
                        majorComboBox.addItem(majorItem);
                    }
                }
            }
        });

        majorComboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    // 获取相应专业对应的班级
                    classComboBox.removeAllItems();
                    String selectedMajor = majorComboBox.getSelectedItem().toString();
                    Query query = new Query(hostIdAddress);
                    query.setDatabaseName("sams");
                    query.setSQL("select distinct class from student where major=" + "'" + selectedMajor + "'");
                    String[][] result = query.getRecord();
                    for (String[] strings : result) {
                        classComboBox.addItem(selectedMajor + strings[0] + "班");
                    }
                }
            }
        });

        add.addActionListener((ActionEvent e) -> {
            String major = majorComboBox.getSelectedItem().toString();
            Integer classNumber = classComboBox.getSelectedIndex() + 1;
            String subject = subjectComboBox.getSelectedItem().toString();
            new GradeAddJFrame(hostIdAddress, major, classNumber, subject).init();
        });
    }

    private class GradeAddJFrame extends JFrame {
        String hostIdAddress;
        String major;
        int classNumber;
        String subject;
        JButton save = new JButton("保存修改");
        JPanel jPanel = new JPanel();

        final int WIDTH = 480;
        final int HEIGHT = 720;

        GradeAddJFrame(String hostIdAddress, String major, int classNumber, String subject) {
            super(major + classNumber + "班" + subject + "成绩录入");
            this.hostIdAddress = hostIdAddress;
            this.major = major;
            this.classNumber = classNumber;
            this.subject = subject;
        }

        private void init() {
            setIconImage(new ImageIcon("images/学生考核.png").getImage());
            setBounds(ScreenUtils.getScreenWidth() / 2 - WIDTH / 2, ScreenUtils.getScreenHeight() / 2 - HEIGHT / 2, WIDTH, HEIGHT);
            JTable jTable;
            String[][] result;
            Query query = new Query(hostIdAddress);
            query.setDatabaseName("sams");
            query.setSQL("select sno, sname from student where major='" + major + "' and class=" + classNumber);
            result = query.getRecord();

            String[][] tableData = new String[result.length][result[0].length + 1];
            for (int i = 0; i < result.length; i++) {
                tableData[i][0] = result[i][0];
                tableData[i][1] = result[i][1];
                tableData[i][2] = null;
            }
            String[] tableHead = new String[]{"学号", "姓名", subject};
            DefaultTableModel defaultTableModel = new DefaultTableModel() {
                @Override
                public boolean isCellEditable(int row, int column) {
                    if (column == 2) return true;
                    else return false;
                }
            };
            defaultTableModel.setDataVector(tableData, tableHead);
            jTable = new JTable(defaultTableModel);
            JTableHeader studentTableHead = jTable.getTableHeader();
            studentTableHead.setPreferredSize(new Dimension(studentTableHead.getWidth(), 35));// 设置表头大小
            studentTableHead.setFont(new Font("楷体", Font.BOLD, 20));// 设置表格字体
            DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
            defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
            jTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
            jTable.setRowHeight(24);  //设置行高
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);// 以下设置表格列宽
            jPanel.setLayout(new BorderLayout());
            jPanel.add(new JScrollPane(jTable));
            jPanel.add(save, BorderLayout.SOUTH);
            add(jPanel);
            setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
            setVisible(true);

            // 表格事件处理
            String[][] newGrade = new String[result.length][3];
            TableModel tableModel = jTable.getModel();
            tableModel.addTableModelListener(new TableModelListener() {
                @Override
                public void tableChanged(TableModelEvent e) {
                    int row = e.getFirstRow();
                    int col = e.getColumn();
                    newGrade[row][0] = (String) tableModel.getValueAt(row, 0);
                    newGrade[row][1] = String.valueOf(SUBJECT.get(subject));
                    newGrade[row][2] = (String) tableModel.getValueAt(row, col);
                }
            });

            save.addActionListener((ActionEvent e) -> {
                Vector<String[]> waitSentData = new Vector<>();
                for (String[] strings : newGrade) {
                    if (strings[0] != null) waitSentData.add(strings);
                }
                String uri =
                        "jdbc:mysql://" + hostIdAddress + ":3306/" +
                                "sams" + "?useSSL=true&characterEncoding=utf-8";
                try {
                    Connection connection = DriverManager.getConnection(uri, "zhang", "123456");
                    Statement statement = connection.createStatement();
                    String sql = null;
                    for (String[] item : waitSentData) {
                        sql = "update sc set grade=" + item[2] + " where sno=" + item[0] + " and cno=" + item[1] + ";";
                        statement.addBatch(sql);
                    }
                    statement.executeBatch();
                    statement.close();
                    JOptionPane.showMessageDialog(this, "成绩录入成功");
                    this.dispose();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            });
        }
    }
}
